package service

import (
	"errors"
	"framework-server/global"
	"framework-server/model"
	"framework-server/model/request"
	"gorm.io/gorm"
)

func GetSysButtonList(info request.GetSysButtonListRequest) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&model.SysButton{})
	var buttonList []model.SysButton

	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}

	if info.Cname != ""{
		db = db.Where("cname LIKE ?", "%"+info.Cname+"%")
	}

	if info.ButtonGroup != ""{
		db = db.Where("buttonGroup LIKE ?", "%"+info.ButtonGroup+"%")
	}
	err = db.Preload("MenuButtonRefer").Count(&total).Error

	if err != nil {
		return err, buttonList, total
	} else {
		db = db.Limit(limit).Offset(offset)
		err = db.Order("button_group").Find(&buttonList).Error
	}
	return err, buttonList, total
}


func GetSysButton(Id uint) (err error, sysButton model.SysButton) {
	err = global.GVA_DB.Where("id = ?", Id).Preload("MenuButtonRefer").First(&sysButton).Error
	return
}

func CreateSysButton(info model.SysButton) (err error) {
	if !errors.Is(global.GVA_DB.Where("name = ?", info.Name).First(&info).Error, gorm.ErrRecordNotFound){
		return errors.New("存在相同按钮名")
	}
	return global.GVA_DB.Create(&info).Error
}


func UpdateSysButton(info model.SysButton) (err error) {
	var sysButtons []model.SysButton
	err = global.GVA_DB.Where("name=? and id != ?", info.Name, info.ID).Find(&sysButtons).Error
	if (err != nil ){
		return
	}
	if (len(sysButtons) != 0){
		err = errors.New("按钮已经存在")
		return err
	}
	err = global.GVA_DB.Save(&info).Error
	return err
}

func DeleteSysButton(info model.SysButton) (err error) {
	err = global.GVA_DB.Delete(info).Error
	return err
}


func GetAllButtons(info request.GetAllButtonsRequest) (err error, buttons []model.SysButton) {
	err = global.GVA_DB.Preload("MenuButtonRefer").Find(&buttons).Error
	if err != nil{
		return err, buttons
	}
	if info.ParentId != "0"{
		err, buttons = GetButtonByAutorityId(info.ParentId)
		return err, buttons

	}
	return nil, buttons
}


func GetButtonByAutorityId(authorityId string)(err error, buttons []model.SysButton) {
	var s model.SysAuthority
	err = global.GVA_DB.Where("authority_id = ?", authorityId).Preload("SysButtons").First(&s).Error

    if err != nil{
    	return err, buttons
	}
	var buttonIds = []uint{}
	for _, v := range s.SysButtons{
		buttonIds = append(buttonIds, v.ID)
	}
	err = global.GVA_DB.Where("id in ?", buttonIds).Preload("MenuButtonRefer").Find(&buttons).Error
	return nil, buttons
}

func AddButtonAuthority(info request.AddButtonAuthorityReqeust)(err error){
	var auth model.SysAuthority
	auth.AuthorityId = info.AuthorityId
	auth.SysButtons = info.Buttons
	err = SetButtonAuthority(&auth)
	if err != nil{
		return
	}
	//同时更新按钮关联的api
	//先获取按钮关联的api列表，再同步到casbin
	buttonIds := []uint{}
	for _, v := range info.Buttons{
		buttonIds = append(buttonIds, v.ID)
	}

	var apis []model.SysApi
	err = global.GVA_DB.Where("buttonId in ? or public = 1", buttonIds).Find(&apis).Error
	if err != nil{
		return
	}
	//再获取原先绑定菜单的api列表
	err, menuApis := GetMenuApiByAuthorityId(info.AuthorityId)
	apis = append(apis, menuApis...)
	var casbinInfos = []request.CasbinInfo{}
	for _, api := range apis{
		casbinInfos = append(casbinInfos, request.CasbinInfo{
			Path: api.Path,
			Method: api.Method,
		})
	}
	err = UpdateCasbin(info.AuthorityId, casbinInfos)
	return err
}